package com.apimarket.util.net;

import com.fasterxml.jackson.databind.JsonNode;
import com.fasterxml.jackson.databind.ObjectMapper;
import org.apache.http.HttpEntity;
import org.apache.http.NameValuePair;
import org.apache.http.client.entity.UrlEncodedFormEntity;
import org.apache.http.client.methods.CloseableHttpResponse;
import org.apache.http.client.methods.HttpPatch;
import org.apache.http.impl.client.CloseableHttpClient;
import org.apache.http.impl.client.HttpClients;
import org.apache.http.message.BasicNameValuePair;
import org.apache.http.util.EntityUtils;

import java.io.IOException;
import java.net.URI;
import java.net.URISyntaxException;
import java.nio.charset.StandardCharsets;
import java.util.*;

public class PatchNetContext extends NetContext {
    private CloseableHttpClient client;

    private HttpPatch httpPatch;

    public PatchNetContext(String url, Map<String, Object> params) {
        super(url, params);
        client = HttpClients.createDefault();
        httpPatch = new HttpPatch();
    }

    private CloseableHttpResponse getResponse() throws IOException, URISyntaxException {
        Map<String, Object> tmp = getParams();
        httpPatch.setURI(new URI(getUrl()));
        if (tmp != null && tmp.size() != 0) {
            List<NameValuePair> nvps = new ArrayList<>();
            Set<String> keys = tmp.keySet();
            Iterator<String> iterator = keys.iterator();
            while (iterator.hasNext()) {
                String key = iterator.next();
                Object val = tmp.get(key);
                nvps.add(new BasicNameValuePair(key, val.toString()));
            }
            httpPatch.setEntity(new UrlEncodedFormEntity(nvps, StandardCharsets.UTF_8));
        }

        return client.execute(httpPatch);
    }


    @Override
    public JsonNode getResultJson() throws IOException, URISyntaxException {
        try (CloseableHttpResponse response = getResponse()) {
            HttpEntity entity = response.getEntity();
            String jsonStr = getJsonStr(entity);
            EntityUtils.consume(entity);
            return new ObjectMapper().readTree(jsonStr);
        }
    }
}
